// pages/phone/phone.js
const app = getApp()
import { getSendSms, bindMobile } from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasUserInfo: false,
    phone: '',
    sms: '',
    sendTime: '获取验证码',
    snsMsgWait: 60
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.userInfo) {
      this.setData({
        hasUserInfo: true
      })
    } 
  },
  onChange (e) {
    this.data.phone = e.detail
  },
  // 获取验证码
  sendCode: function () {
    // 60秒后重新获取验证码
    var inter = setInterval(function () {
      this.setData({
        smsFlag: true,
        sendTime: this.data.snsMsgWait + 's',
        snsMsgWait: this.data.snsMsgWait - 1
      });
      if (this.data.snsMsgWait <= 0) {
        clearInterval(inter)
        this.setData({
          sendTime: '获取验证码',
          snsMsgWait: 60,
          smsFlag: false
        });
      }
    }.bind(this), 1000);
  },
  smsClick () {
    let _this = this
    let phone = _this.data.phone
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      wx.showToast({
        title: '手机号码不合法！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    getSendSms({ mobile: phone }).then(res => {
      if(res.code == 200) {
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 1500
        })
      }
      _this.sendCode()
    })
  },
  onChange2(e) {
    this.data.sms = e.detail
  },
  subClick () {
    let _this = this
    let sms = _this.data.sms
    if (sms == '') {
      wx.showToast({
        title: '请填写验证码！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    bindMobile({ openid: app.globalData.openid, mobile: _this.data.phone, verif_code: sms}).then(res => {
      if(res.code == 200) {
        wx.showToast({
          title: '绑定成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})